<template>
  <div class="app-container">
    <!-- 搜索表单区域（保留原始功能） -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="开课学期" prop="semester">
        <el-select v-model="queryParams.semester" placeholder="请选择开课学期" clearable style="width: 200px;">
          <el-option v-for="dict in semester" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择年级" clearable style="width: 200px;">
          <el-option v-for="dict in grade" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="学年" prop="academicYear">
        <el-select v-model="queryParams.academicYear" placeholder="请选择学年" clearable style="width: 200px;">
          <el-option v-for="dict in academic_year" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级名称" prop="className">
        <el-input v-model="queryParams.className" placeholder="请输入班级名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="开课院系" prop="department">
        <el-input v-model="queryParams.department" placeholder="请输入开课院系" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="校区" prop="campus">
        <el-select v-model="queryParams.campus" placeholder="请选择校区" clearable style="width: 200px;">
          <el-option v-for="dict in campus_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开课周期" prop="coursePeriod">
        <el-input v-model="queryParams.coursePeriod" placeholder="请输入开课周期" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="是否排课完成" prop="isScheduleCompleted">
        <el-select v-model="queryParams.isScheduleCompleted" placeholder="请选择是否排课完成" clearable style="width: 200px;">
          <el-option v-for="dict in y_n" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格区域：核心优化操作栏显示逻辑（保留v-hasPermi+叠加角色判断） -->
    <el-table v-loading="loading" :data="detailsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="班级名称" align="center" prop="className" width="150" />
      <el-table-column label="开课学期" align="center" prop="semester" width="150">
        <template #default="scope"><dict-tag :options="semester" :value="scope.row.semester"/></template>
      </el-table-column>
      <el-table-column label="年级" align="center" prop="grade">
        <template #default="scope"><dict-tag :options="grade" :value="scope.row.grade"/></template>
      </el-table-column>
      <el-table-column label="学年" align="center" prop="academicYear">
        <template #default="scope"><dict-tag :options="academic_year" :value="scope.row.academicYear"/></template>
      </el-table-column>
      <el-table-column label="开课院系" align="center" prop="department">
        <template #default="scope">{{ scope.row.departmentId || "未知院系" }}</template>
      </el-table-column>
      <el-table-column label="班级最大容量" align="center" prop="maxCapacity" />
      <el-table-column label="已选学生人数" align="center" prop="currentEnrollment" />
      <el-table-column label="班级状态" align="center" prop="status">
        <template #default="scope"><dict-tag :options="schedule_class_status" :value="scope.row.status"/></template>
      </el-table-column>
      <el-table-column label="是否排课完成" align="center" prop="isScheduleCompleted">
        <template #default="scope">
          <span :class="{
            'highlight-completed': scope.row.isScheduleCompleted === 1,
            'highlight-not-completed': scope.row.isScheduleCompleted === 0
          }" style="padding: 2px 6px; border-radius: 4px; display: inline-block;">
            <dict-tag :options="y_n_course" :value="scope.row.isScheduleCompleted"/>
          </span>
        </template>
      </el-table-column>

      <!-- 操作栏：核心优化——v-hasPermi + 角色+排课状态判断 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 动态按钮：排课完成→查看，未完成→填写 -->
          <el-button
              link
              type="primary"
              :icon="scope.row.isScheduleCompleted === 1 ? 'Eye' : 'Edit'"
              @click="handleCourseDetail(scope.row)"
              v-hasPermi="['trainingManagement:details:edit']"
              v-if="shouldShowButton(scope.row, 'trainingManagement:details:edit')"
              style="margin-right: 8px;"
          >
            {{ scope.row.isScheduleCompleted === 1 ? '查看排课信息' : '填写课程详细信息' }}
          </el-button>
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleInputScore(scope.row)"
              v-if="shouldShowButton(scope.row, 'trainingManagement:details:inputScore')"
          >
            录入成绩
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件：修改为前端分页触发事件 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handlePagination" 
    />

    <!-- 课程详情弹窗（保留原始功能） -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="detailsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="开课班ID" prop="trainingProgramCoursesId">
          <el-input v-model="form.trainingProgramCoursesId" placeholder="请输入开课班ID" />
        </el-form-item>
        <el-form-item label="课程ID" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程ID" />
        </el-form-item>
        <el-form-item label="培养方案ID" prop="trainingProgramId">
          <el-input v-model="form.trainingProgramId" placeholder="请输入培养方案ID" />
        </el-form-item>
        <el-form-item label="开课学期" prop="semester">
          <el-select v-model="form.semester" placeholder="请选择开课学期">
            <el-option v-for="dict in semester" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择年级">
            <el-option v-for="dict in grade" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学年" prop="academicYear">
          <el-select v-model="form.academicYear" placeholder="请选择学年">
            <el-option v-for="dict in academic_year" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="关联行政班ID" prop="administrativeClassId">
          <el-input v-model="form.administrativeClassId" placeholder="请输入关联行政班ID" />
        </el-form-item>
        <el-form-item label="开课院系" prop="department">
          <el-input v-model="form.department" placeholder="请输入开课院系" />
        </el-form-item>
        <el-form-item label="校区" prop="campus">
          <el-select v-model="form.campus" placeholder="请选择校区">
            <el-option v-for="dict in campus_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教室" prop="classroom">
          <el-input v-model="form.classroom" placeholder="请输入教室" />
        </el-form-item>
        <el-form-item label="上课时间段" prop="timeSlot">
          <el-select v-model="form.timeSlot" placeholder="请选择上课时间段">
            <el-option v-for="dict in class_time_period" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级最大容量" prop="maxCapacity">
          <el-input v-model="form.maxCapacity" type="number" placeholder="请输入班级最大容量" />
        </el-form-item>
        <el-form-item label="已选学生人数" prop="currentEnrollment">
          <el-input v-model="form.currentEnrollment" type="number" placeholder="请输入已选学生人数" />
        </el-form-item>
        <el-form-item label="班级状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择班级状态">
            <el-option v-for="dict in schedule_class_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开课周期" prop="coursePeriod">
          <el-input v-model="form.coursePeriod" placeholder="请输入开课周期" />
        </el-form-item>
        <el-form-item label="教学方式" prop="teachingMode">
          <el-select v-model="form.teachingMode" placeholder="请选择教学方式">
            <el-option v-for="dict in teaching_method" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教学大纲文件路径" prop="syllabus">
          <el-input v-model="form.syllabus" placeholder="请输入教学大纲文件路径" />
        </el-form-item>
        <el-form-item label="是否已完成分班" prop="isClassAssigned">
          <el-select v-model="form.isClassAssigned" placeholder="请选择是否已完成分班">
            <el-option v-for="dict in y_n_course" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程类型" prop="courseType">
          <el-select v-model="form.courseType" placeholder="请选择课程类型">
            <el-option v-for="dict in type_of_course" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否班级满员" prop="isFull">
          <el-select v-model="form.isFull" placeholder="请选择是否班级满员">
            <el-option v-for="dict in y_n" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否排课完成" prop="isScheduleCompleted">
          <el-select v-model="form.isScheduleCompleted" placeholder="请选择是否排课完成">
            <el-option v-for="dict in y_n" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排课时间" prop="scheduledAt">
          <el-date-picker clearable v-model="form.scheduledAt" type="date" value-format="YYYY-MM-DD" placeholder="请选择排课时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="排课优先级" prop="schedulePriority">
          <el-select v-model="form.schedulePriority" placeholder="请选择排课优先级">
            <el-option v-for="dict in schedule_priority" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上课周几" prop="weekDay">
          <el-select v-model="form.weekDay" placeholder="请选择上课周几">
            <el-option v-for="dict in week" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级介绍或备注" prop="classDescription">
          <el-input v-model="form.classDescription" type="textarea" placeholder="请输入内容" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 自动排课弹窗（保留原始功能） -->
    <el-dialog :title="autoScheduleTitle" v-model="autoScheduleOpen" width="600px" append-to-body>
      <el-form ref="autoScheduleRef" :model="autoScheduleForm" :rules="autoScheduleRules" label-width="120px">
        <el-form-item label="课程班名称" prop="className">
          <el-input v-model="autoScheduleForm.className" placeholder="课程班名称" disabled />
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="autoScheduleForm.courseName" placeholder="课程名称" disabled />
        </el-form-item>
        <el-form-item label="选择教师" prop="teacherId">
          <el-select v-model="autoScheduleForm.teacherId" placeholder="请选择教师" filterable>
            <el-option v-for="teacher in filteredTeachers" :key="teacher.id" :label="teacher.name" :value="teacher.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="校区" prop="campus">
          <el-select v-model="autoScheduleForm.campus" placeholder="请选择校区">
            <el-option v-for="dict in campus_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教室类型" prop="roomType">
          <el-select v-model="autoScheduleForm.roomType" placeholder="请选择教室类型" clearable filterable>
            <el-option v-for="dict in classroom_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="每节课课时数" prop="lessonCount">
          <el-input v-model.number="autoScheduleForm.lessonCount" type="number" min="1" placeholder="请输入每节课课时数" />
        </el-form-item>
        <el-form-item label="周次数" prop="weekType">
          <el-input v-model.number="autoScheduleForm.weekType" type="number" min="1" max="3" placeholder="一周上几次课（1-3）" />
        </el-form-item>
        <el-form-item label="开始周" prop="startWeek">
          <el-input v-model.number="autoScheduleForm.startWeek" type="number" min="1" max="20" placeholder="请输入开始周（1-20）" />
        </el-form-item>
        <el-form-item label="结束周" prop="end_week">
          <el-input v-model.number="autoScheduleForm.end_week" type="number" min="1" max="20" placeholder="请输入结束周（1-20）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAutoSchedule">确 定</el-button>
          <el-button @click="cancelAutoSchedule">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Details">
// 1. 导入必要依赖（补充原始代码缺失的computed、onMounted）
import { listDetails, getDetails, delDetails, addDetails, updateDetails, commitDetails, assignTeacher } from "@/api/trainingManagement/details";
import { selectCourseScheduleDetailsList } from "@/api/student/allList";
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'; // 补充关键依赖
import { listTeacher } from "@/api/teacher/teacher";
import { loadAllParams } from "@/api/page";
import { debounce } from 'lodash-es';
import { listCourse } from "@/api/course/course";
import { useRouter } from 'vue-router';
import useUserStore from '@/store/modules/user';
import { CourseScheduleDetailsList } from '@/api/course/availability';

// 2. 初始化核心实例与工具
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const router = useRouter();

// 3. 字典数据（保留原始逻辑）
const { campus_type, week, type_of_course, semester, y_n, schedule_priority, class_time_period, teaching_method, grade, schedule_class_status, academic_year, classroom_type, y_n_course } = proxy.useDict(
    'campus_type', 'week', 'type_of_course', 'semester', 'y_n', 'schedule_priority',
    'class_time_period', 'teaching_method', 'grade', 'schedule_class_status', 'academic_year',
    'classroom_type', 'y_n_course'
);

// 4. 响应式数据（新增全量数据和过滤后数据存储）
const detailsList = ref([]); // 当前页数据（表格显示用）
const allDetailsList = ref([]); // 全量数据（前端分页数据源）
const filteredDetailsList = ref([]); // 搜索过滤后的全量数据
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const courseNameMap = ref({});
const autoScheduleOpen = ref(false);
const autoScheduleTitle = ref("填写自动排课信息");
const isViewMode = ref(false);

// 5. 自动排课表单与规则（保留原始逻辑，补充字段验证）
const autoScheduleForm = reactive({
  id: null,
  className: '',
  courseName: '',
  teacherId: null,
  schedulePriority: null,
  scheduleRemark: '',
  roomType: null,
  lessonCount: null,
  weekType: null,
  startWeek: null,
  end_week: null
});
const autoScheduleRules = reactive({
  teacherId: [{ required: true, message: "请选择教师", trigger: "change" }],
  schedulePriority: [{ required: true, message: "请选择排课优先级", trigger: "change" }],
  roomType: [{ required: true, message: "请选择教室类型", trigger: "change" }],
  lessonCount: [{ required: true, message: "请输入每节课课时数", trigger: "blur" }],
  weekType: [{ required: true, message: "请输入周次数", trigger: "blur" }],
  startWeek: [{ required: true, message: "请输入开始周", trigger: "blur" }],
  end_week: [{ required: true, message: "请输入结束周", trigger: "blur" }]
});

// 6. 核心数据（查询参数+表单，保留原始逻辑）
const data = reactive({
  form: {
    id: null,
    trainingProgramCoursesId: null,
    courseId: null,
    trainingProgramId: null,
    semester: null,
    grade: null,
    className: null,
    administrativeClassId: null,
    department: null,
    campus: null,
    classroom: null,
    timeSlot: null,
    maxCapacity: null,
    currentEnrollment: null,
    status: null,
    coursePeriod: null,
    teachingMode: null,
    syllabus: null,
    isClassAssigned: null,
    courseType: null,
    isCrossSemester: null,
    isFull: null,
    isScheduleCompleted: null,
    scheduledAt: null,
    schedulePriority: null,
    weekDay: null,
    classDescription: null,
    createdAt: null,
    updatedAt: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    trainingProgramCoursesId: null,
    courseId: null,
    trainingProgramId: null,
    semester: null,
    grade: null,
    className: null,
    administrativeClassId: null,
    department: null,
    campus: null,
    classroom: null,
    timeSlot: null,
    maxCapacity: null,
    currentEnrollment: null,
    status: null,
    coursePeriod: null,
    teachingMode: null,
    syllabus: null,
    isClassAssigned: null,
    courseType: null,
    isCrossSemester: null,
    isFull: null,
    isScheduleCompleted: null,
    scheduledAt: null,
    schedulePriority: null,
    weekDay: null,
    classDescription: null,
    createdAt: null,
    updatedAt: null,
    academicYear: null
  },
  rules: {
    trainingProgramCoursesId: [{ required: true, message: "开课班ID不能为空", trigger: "blur" }],
    courseId: [{ required: true, message: "课程ID不能为空", trigger: "blur" }],
    trainingProgramId: [{ required: true, message: "培养方案ID不能为空", trigger: "blur" }],
    semester: [{ required: true, message: "开课学期不能为空", trigger: "change" }],
    grade: [{ required: true, message: "年级不能为空", trigger: "change" }],
    className: [{ required: true, message: "班级名称不能为空", trigger: "blur" }],
    administrativeClassId: [{ required: true, message: "关联行政班ID不能为空", trigger: "blur" }],
    department: [{ required: true, message: "开课院系不能为空", trigger: "blur" }],
    campus: [{ required: true, message: "校区不能为空", trigger: "change" }],
    classroom: [{ required: true, message: "教室不能为空", trigger: "blur" }],
    timeSlot: [{ required: true, message: "上课时间段不能为空", trigger: "change" }],
    maxCapacity: [{ required: true, message: "班级最大容量不能为空", trigger: "blur" }],
    status: [{ required: true, message: "班级状态不能为空", trigger: "change" }],
  }
});
const { queryParams, form, rules } = toRefs(data);
const teacherList = ref([]);
const filteredTeachers = ref([]);

// -------------------------- 核心优化1：角色判断（兼容多格式） --------------------------
// 仅用于判断是否为教师角色，不参与权限判断（权限仍由v-hasPermi控制）
const isTeacher = computed(() => {
  const userRoles = userStore.roles || '';
  // 兼容角色为数组（如["teacher"]）或字符串（如"teacher,admin"）的情况
  if (Array.isArray(userRoles)) {
    return userRoles.some(role => String(role).toLowerCase() === 'teacher');
  }
  return String(userRoles).toLowerCase().includes('teacher');
});

// -------------------------- 核心优化2：按钮显示逻辑（叠加角色+排课状态） --------------------------
// 功能：在v-hasPermi通过的基础上，进一步判断是否符合角色对应的显示规则
const shouldShowButton = (row, permission) => {
  // 1. 先通过v-hasPermi确保有权限（此函数仅叠加判断，不替代权限指令）
  // 2. 教师角色：需额外判断排课状态为“已完成”（isScheduleCompleted === 1）
  if (isTeacher.value) {
    const isScheduleDone = row.isScheduleCompleted === 1;
    console.log(`教师角色[${permission}]：排课${isScheduleDone ? '已完成（显示）' : '未完成（隐藏）'}`);
    return isScheduleDone;
  }
  // 3. 非教师角色：有权限即显示（无需排课状态判断）
  console.log(`非教师角色[${permission}]：有权限（显示）`);
  return true;
};

// -------------------------- 核心优化3：前端分页核心函数 --------------------------
// 功能：根据pageNum和pageSize截取当前页数据
const handlePagination = () => {
  const { pageNum, pageSize } = queryParams.value;
  // 计算截取索引（避免越界）
  const startIndex = Math.max(0, (pageNum - 1) * pageSize);
  const endIndex = startIndex + pageSize;
  // 从过滤后的数据中截取当前页数据
  detailsList.value = filteredDetailsList.value.slice(startIndex, endIndex);
  // 总条数 = 过滤后的数据条数（分页组件显示总页数用）
  total.value = filteredDetailsList.value.length;
};

// -------------------------- 原有方法：表单操作（保留原始逻辑，修复小问题） --------------------------
function cancel() {
  open.value = false;
  reset();
}

function cancelAutoSchedule() {
  autoScheduleOpen.value = false;
  resetAutoScheduleForm();
}

function resetAutoScheduleForm() {
  autoScheduleForm.id = null;
  autoScheduleForm.className = '';
  autoScheduleForm.courseName = '';
  autoScheduleForm.teacherId = null;
  autoScheduleForm.schedulePriority = null;
  autoScheduleForm.scheduleRemark = '';
  autoScheduleForm.roomType = null;
  autoScheduleForm.lessonCount = null;
  autoScheduleForm.weekType = null;
  autoScheduleForm.startWeek = null;
  autoScheduleForm.end_week = null;
  proxy.resetForm("autoScheduleRef");
}

function reset() {
  form.value = { ...data.form }; // 重置为初始值，避免引用问题
  proxy.resetForm("detailsRef");
}

// -------------------------- 优化后：搜索功能（前端过滤+分页） --------------------------
function handleQuery() {
  // 1. 搜索后重置为第1页
  queryParams.value.pageNum = 1;

  // 2. 提取所有搜索条件
  const { semester, grade, academicYear, className, department, campus, coursePeriod, isScheduleCompleted } = queryParams.value;

  // 3. 前端过滤全量数据（满足所有非空条件）
  filteredDetailsList.value = allDetailsList.value.filter(item => {
    // 精确匹配：学期、年级、学年、校区、排课完成状态
    const matchSemester = semester ? item.semester === semester : true;
    const matchGrade = grade ? item.grade === grade : true;
    const matchAcademicYear = academicYear ? item.academicYear === academicYear : true;
    const matchCampus = campus ? item.campus === campus : true;
    const matchIsCompleted = isScheduleCompleted !== null ? item.isScheduleCompleted === Number(isScheduleCompleted) : true;

    // 模糊匹配：班级名称、开课院系、开课周期（忽略大小写）
    const matchClassName = className ? item.className?.toLowerCase().includes(className.toLowerCase()) : true;
    const matchDepartment = department ? item.departmentId?.toLowerCase().includes(department.toLowerCase()) : true;
    const matchCoursePeriod = coursePeriod ? item.coursePeriod?.toLowerCase().includes(coursePeriod.toLowerCase()) : true;

    // 所有条件同时满足才保留
    return matchSemester && matchGrade && matchAcademicYear && matchCampus && matchIsCompleted && matchClassName && matchDepartment && matchCoursePeriod;
  });

  // 4. 触发前端分页（显示过滤后的第1页）
  handlePagination();
}

// -------------------------- 优化后：重置功能（恢复全量数据分页） --------------------------
function resetQuery() {
  proxy.resetForm("queryRef");
  // 重置所有搜索条件为null（保留pageNum和pageSize）
  Object.keys(queryParams.value).forEach(key => {
    if (!['pageNum', 'pageSize'].includes(key)) {
      queryParams.value[key] = null;
    }
  });
  // 重置为第1页
  queryParams.value.pageNum = 1;
  // 过滤后数据 = 全量数据（恢复无搜索状态）
  filteredDetailsList.value = [...allDetailsList.value];
  // 触发分页
  handlePagination();
}

// -------------------------- 原有方法：表格选择、增删改查（保留原始逻辑） --------------------------
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加课程排课详细信息";
}

function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getDetails(_id).then(response => {
    form.value = { ...response.data }; // 深拷贝，避免修改原数据
    open.value = true;
    title.value = "修改课程排课详细信息";
  }).catch(error => {
    console.error("获取详情失败：", error);
    proxy.$modal.msgError("获取课程详情失败");
  });
}

function submitForm() {
  proxy.$refs["detailsRef"].validate(valid => {
    if (valid) {
      const submitFn = form.value.id ? updateDetails : addDetails;
      submitFn(form.value).then(response => {
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
        open.value = false;
        getList(); // 新增/修改后重新加载全量数据
      }).catch(error => {
        console.error("提交失败：", error);
        proxy.$modal.msgError(form.value.id ? "修改失败" : "新增失败");
      });
    }
  });
}

function handleDelete(row) {
  const _ids = row.id || ids.value;
  if (!_ids.length) {
    proxy.$modal.msgWarning("请选择要删除的数据");
    return;
  }
  proxy.$modal.confirm(`是否确认删除课程排课详细信息编号为"${_ids}"的数据项？`).then(() => {
    return delDetails(_ids);
  }).then(() => {
    getList(); // 删除后重新加载全量数据
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

function handleExport() {
  proxy.download('trainingManagement/details/export', { ...queryParams.value }, `课程排课详情_${new Date().getTime()}.xlsx`);
}

// -------------------------- 原有方法：教师列表与自动排课（保留原始逻辑） --------------------------
const getTeacherList = async () => {
  try {
    if (teacherList.value.length === 0) {
      const res = await listTeacher({ loadAllParams });
      teacherList.value = res.rows;
      filteredTeachers.value = res.rows;
    }
  } catch (err) {
    console.error('教师数据加载失败:', err);
    proxy.$modal.msgError("教师列表加载失败");
  }
};

async function automaticCourseScheduling(row) {
  if (!row) {
    proxy.$modal.msgWarning("课程信息不存在，无法填写排课信息");
    return;
  }
  resetAutoScheduleForm();
  await getTeacherList();
  autoScheduleForm.id = row.id;
  autoScheduleForm.className = row.className || '';
  autoScheduleForm.courseName = row.courseName || '';
  autoScheduleForm.teacherId = row.teacherId || null;
  autoScheduleForm.schedulePriority = row.schedulePriority || null;
  autoScheduleOpen.value = true;
}

function submitAutoSchedule() {
  proxy.$refs["autoScheduleRef"].validate(valid => {
    if (valid) {
      const updateData = {
        id: autoScheduleForm.id,
        teacherId: autoScheduleForm.teacherId,
        schedulePriority: autoScheduleForm.schedulePriority,
        roomType: autoScheduleForm.roomType,
        lessonCount: autoScheduleForm.lessonCount,
        weekType: autoScheduleForm.weekType,
        startWeek: autoScheduleForm.startWeek,
        endWeek: autoScheduleForm.end_week
      };
      updateDetails(updateData).then(response => {
        proxy.$modal.msgSuccess("自动排课信息保存成功");
        autoScheduleOpen.value = false;
        getList(); // 保存后重新加载全量数据
      }).catch(error => {
        console.error("排课保存失败:", error);
        proxy.$modal.msgError("排课信息保存失败，请重试");
      });
    }
  });
}

const filterTeachers = debounce(async (query) => {
  if (!query) {
    filteredTeachers.value = teacherList.value;
    return;
  }
  const lowerQuery = query.trim().toLowerCase();
  filteredTeachers.value = teacherList.value.filter(teacher =>
      teacher.name?.toLowerCase().includes(lowerQuery) ||
      teacher.teacherCode?.includes(query)
  );
}, 300);

// -------------------------- 原有方法：页面跳转（保留原始逻辑） --------------------------
function handleInputScore(row) {
  if (!row) {
    proxy.$modal.msgWarning("课程信息不存在，无法录入成绩");
    return;
  }
  router.push({
    name: 'ScoreInput',
    query: {
      courseScheduleDetailsId: row.id,
      className: row.className,
      courseName: row.courseName,
      semester: row.semester,
      grade: row.grade
    }
  });
}

function handleCourseDetail(row) {
  try {
    if (!row) {
      proxy.$modal.msgWarning("课程信息不存在，无法跳转");
      return;
    }
    router.push({
      path: '/detailedCourseInformation',
      query: { rowData: JSON.stringify(row) }
    });
  } catch (error) {
    console.error("跳转详情页失败：", error);
    proxy.$modal.msgError("跳转失败，请重试");
  }
}

// -------------------------- 优化后：列表加载（仅加载一次全量数据） --------------------------
const fetchCourseNames = async () => {
  try {
    const res = await listCourse({ pageSize: 2000 });
    courseNameMap.value = res.rows.reduce((map, course) => {
      const courseIdStr = String(course.id);
      map[courseIdStr] = {
        name: course.courseName || "未命名课程",
        department: course.departmentId || "未知院系"
      };
      return map;
    }, {});
  } catch (error) {
    console.error("获取课程列表失败：", error);
    proxy.$modal.msgError("课程信息加载失败，请刷新页面重试");
  }
};

async function getList() {
  loading.value = true;
  try {
    // 1. 加载课程名称映射（用于表格显示课程名称和院系）
    await fetchCourseNames();

    // 2. 调用接口获取全量数据（仅加载一次）
    const response = await CourseScheduleDetailsList();
    console.log("接口返回全量数据：", response);

    // 3. 数据处理：补充课程名称和院系字段
    const fullScheduleData = response.rows || [];
    allDetailsList.value = fullScheduleData.map(item => {
      const courseIdStr = String(item.courseId);
      const courseInfo = courseNameMap.value[courseIdStr] || {
        name: "未知课程",
        department: "未知院系"
      };
      return {
        ...item,
        courseName: courseInfo.name,
        departmentId: courseInfo.department
      };
    });

    // 4. 初始化：过滤后数据 = 全量数据（无搜索条件）
    filteredDetailsList.value = [...allDetailsList.value];

    // 5. 触发前端分页（显示第1页数据）
    handlePagination();

    // 调试信息
    console.log('全量数据条数:', allDetailsList.value.length, '当前用户角色:', userStore.roles, '是否为教师:', isTeacher.value);

  } catch (error) {
    console.error("列表加载失败：", error);
    proxy.$modal.msgError("排课列表加载失败，请刷新页面重试");
    allDetailsList.value = [];
    filteredDetailsList.value = [];
    detailsList.value = [];
    total.value = 0;

  } finally {
    loading.value = false;
  }
}

// -------------------------- 初始化加载（保留原始逻辑） --------------------------
onMounted(async () => {
  await fetchCourseNames();
  getList(); // 仅加载一次全量数据
});

// 初始加载列表
getList();
</script>

<style scoped>
/* 保留原始样式，优化按钮间距 */
.mb8 {
  margin-bottom: 8px;
}

.highlight-completed {
  background-color: #c3f6c5;
  color: #009900;
}

.highlight-not-completed {
  background-color: #ffd6d6;
  color: #ff0000;
}

/* 优化操作栏按钮间距，避免重叠 */
.el-button + .el-button {
  margin-left: 8px;
}

.small-padding {
  padding: 0 5px;
}

.fixed-width {
  width: 320px; /* 确保操作栏有足够宽度显示两个按钮 */
}
</style>